<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/4
 * Time: 11:10
 */

namespace app\common\utils;


use app\common\utils\wechat\WechatPay;

class WeChatSendRedPackUtils
{
    const MCHID = "1500332342";
    const APPID = "wxbdebf4bd5d1cf85b";
    const KEY = "7c156207f2f67d74ef1b8b81490a4f71";
    const SSLCERT_PATH = "/www/RedEnvelope/extend/wxpay/cert/apiclient_cert.pem";//证书地址   *****   此处要写服务器绝对路径
    const SSLKEY_PATH = "/www/RedEnvelope/extend/wxpay/cert/apiclient_key.pem";//证书地址
    /**
     * 发送红包
     * @param $open_id string openid
     * @param $total_num float 金额
     * @param $send_name string 商户名称
     * @param $wishing string 红包祝福语
     * @param $act_name string 活动名
     * @param $remark string 备注
     * @return mixed
     */
    public function sendRedPack($open_id,$total_num,$send_name,$wishing,$act_name,$remark) {
        $config = [
//            'token'          => 'test',
            'appid'          => self::APPID,
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id'         => self::MCHID,
            'partnerkey'        => self::KEY,
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key'        => self::SSLKEY_PATH,
            'ssl_cer'        => self::SSLCERT_PATH,
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path'     => '',
        ];
        $utils = new WechatPay($config);
        $mch_billno = $this->gen_mch_billno();
        $json = $utils->sendRedPack($open_id,$total_num,$mch_billno,$send_name,$wishing,$act_name,$remark);
        return $json;
    }

    private function gen_mch_billno(){
        //生成一个长度10，的阿拉伯数字随机字符串
        $rnd_num = array('0','1','2','3','4','5','6','7','8','9');
        $rndstr = "";
        while(strlen($rndstr)<10){
            $rndstr .= $rnd_num[array_rand($rnd_num)];
        }
        return self::MCHID.date("Ymd").$rndstr;
    }
}